package com.maiji.cloud.configSecurity;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.maiji.cloud.entities.manager.User;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.UserService;
import com.maiji.cloud.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 *  Spring Security默认是禁用注解的，要想开启注解，需要在继承WebSecurityConfigurerAdapter的类上加@EnableGlobalMethodSecurity注解，
 *  来判断用户对某个控制层的方法是否具有访问权限
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;
    @Autowired
    MyMetadataSource myMetadataSource;
    @Autowired
    MyAccessDecisionManager myAccessDecisionManager;
    @Autowired
    AuthenticationAccessDeniedHandler deniedHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/order/findUserOrdersByToken", "/goods/findAllGoods", "/userInterface/getUserInfo",
                "/deitInterface/getDietLog", "/userInterface/getWeightChangeLogList", "/userInterface/getKetonuria", "/favicon.ico",
                "/swagger**/**","/webjars**/**", "/images**/**", "/v2**/**", "/configuration**/**", "/index.html", "/static/**", "/login_p");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(myMetadataSource);
                        o.setAccessDecisionManager(myAccessDecisionManager);
                        return o;
                    }
                })
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .usernameParameter("name")
                .passwordParameter("pwd")
                .failureHandler( (HttpServletRequest req, HttpServletResponse resp, AuthenticationException e)  -> {
                        resp.setContentType("application/json;charset=utf-8");
                        BaseResDto respBean;
                        if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
                        respBean = new BaseResDto(Status.ERROR).setMessage("账户名或者密码输入错误!");
                        }
                        else if (e instanceof LockedException) {
                        respBean = new BaseResDto(Status.ERROR).setMessage("账户被锁定，请联系管理员!");
                        }
                        else if (e instanceof CredentialsExpiredException) {
                        respBean = new BaseResDto(Status.ERROR).setMessage("密码过期，请联系管理员!");
                        }
                        else if (e instanceof AccountExpiredException) {
                        respBean = new BaseResDto(Status.ERROR).setMessage("账户过期，请联系管理员!");
                        }
                        else if (e instanceof DisabledException) {
                        respBean = new BaseResDto(Status.ERROR).setMessage("账户被禁用，请联系管理员!");
                        } else {
                        respBean = new BaseResDto(Status.ERROR).setMessage("登录失败!");
                        }
                        ObjectMapper om = new ObjectMapper();
                        PrintWriter out = resp.getWriter();
                        out.write(om.writeValueAsString(respBean));
                        out.flush();
                        out.close();
                })
                .successHandler((HttpServletRequest req, HttpServletResponse resp, Authentication auth) -> {
                        resp.setContentType("application/json;charset=utf-8");
                        BaseDataResDto<User> respBean = new BaseDataResDto(Status.SUCCESS.setMessage("登录成功")).setData(UserUtil.getCurrentUser());
                        ObjectMapper om = new ObjectMapper();
                        PrintWriter out = resp.getWriter();
                        out.write(om.writeValueAsString(respBean));
                        out.flush();
                        out.close();
                })
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((HttpServletRequest req, HttpServletResponse resp, Authentication authentication) -> {
                        resp.setContentType("application/json;charset=utf-8");
                        BaseResDto respBean = new BaseResDto(Status.SUCCESS).setMessage("注销成功!");
                        ObjectMapper om = new ObjectMapper();
                        PrintWriter out = resp.getWriter();
                        out.write(om.writeValueAsString(respBean));
                        out.flush();
                        out.close();
                })
                .permitAll()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .accessDeniedHandler(deniedHandler);
    }

}